#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LEN 20
#define MAX_FRUIT_CLS 20
#define MAX_PATH 256

typedef struct{
    char name[MAX_NAME_LEN];
    float in;
    float out;
}FInfo, *pFInfo;

int loadStock(pFInfo, const char *);
void sortAndSaveStock(pFInfo, int, char *);
int comp(const void *, const void *);

void catout(FILE *);
void checkout(const char *fname);

int main()
{
    FInfo fruitStock[MAX_FRUIT_CLS];
    char fname[MAX_PATH] = {0};
    int no, n;

    scanf("%d", &no);
    sprintf(fname, "record%d.dic", no);
    n = loadStock(fruitStock, fname);
    sprintf(fname, "sorted_record%d.dic", no);
    if ( n > 0)  sortAndSaveStock(fruitStock, n, fname);
    checkout(fname);
    return 0;
}

void catout(FILE *fp)
{
    char line[MAX_PATH]={0};

    rewind(fp);
    while( ! feof(fp))
    {
        if (fgets(line, MAX_PATH, fp) == NULL)
            break;
        printf("%s",line);
        memset(line, 0, MAX_PATH);
    }
}

void checkout(const char *fname)
{
    FILE *fp;
    int len = 0;

    fp = fopen(fname,"r");
    if (!fp) return;
    fseek(fp, 0L, SEEK_END);
    len = (int) ftell(fp);

    printf("File Len = %d.\n", len);
    catout(fp);
    fclose(fp);
}

/* 缓冲区大小 */
#define MAX_STR_LEN 2048

/* 读取库存数据 */
int loadStock(pFInfo stocks, const char *fname)
{
    FILE *fp;
    int i, n;
    /* 一行数据缓冲区 */
    char s[MAX_STR_LEN] = {0};

    /* 以读方式打开文本文件 */
    fp = fopen(fname, "r");
    if(fp == NULL)
    {
        return -1;
    }

    i = 0;
    while(NULL != fgets(s, MAX_STR_LEN, fp))
    {
        /* 从字符串中读入数据 */
        n = sscanf(s, "%s%f%f", stocks->name, &stocks->in, &stocks->out);
        memset(s, 0, MAX_STR_LEN);

        /* 读取字段数正常 */
        if (n >= 3)
        {
            stocks++;
            i++;
        }
        else
        {
            break;
        }
    }

    /* 关闭文件 */
    fclose(fp);

    return i;
}

/* qsort排序的比较函数 */
int cmp(const void *p, const void *q)
{
    const pFInfo p1 = (const pFInfo)p;
    const pFInfo q1 = (const pFInfo)q;

    float st1 = p1->in - p1->out;
    float st2 = q1->in - q1->out;

    return (st1 < st2) - (st1 > st2);
}

/* 库存排序及保存 */
void sortAndSaveStock(pFInfo stocks, int n, char *fname)
{
    FILE *fp;
    /* 一行文本缓冲区 */
    char s[MAX_STR_LEN] = {0};
    int i;

    /* 以写的方式打开文本文件 */
    fp = fopen(fname, "w");
    if(fp == NULL)
    {
        return;
    }

    /* 对库存排序 */
    qsort(stocks, n, sizeof(stocks[0]), cmp);

    /* 将结果写入文本文件 */
    for(i = 0; i < n - 1; i++)
    {
        /* 先写入缓冲区 */
        sprintf(s, "%s %0.1f %0.1f\n", stocks[i].name, stocks[i].in, stocks[i].out);
        /* 再写入文件 */
        fputs(s, fp);
    }
    /* 最后一行不写入'\n' */
    sprintf(s, "%s %0.1f %0.1f", stocks[i].name, stocks[i].in, stocks[i].out);
    fputs(s, fp);

    /* 关闭文件 */
    fclose(fp);
}
